/*******************************************************************************
 * Licensed to the OKChem
 *
 * http://www.okchem.com
 *
 *******************************************************************************/
package com.lz.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * Created by toy lv on 2018/1/11 0011.
 *
 * @author:toy lv
 * @DATE:2018/1/11 0011
 */
@Service
public class SecKillService {

    private static final int TIMEOUT = 10*1000;

    @Autowired
    private RedisLock redisLock;

    static Map<String, Integer> products;

    static Map<String, Integer> stock;

    static Map<String, String> orders;

    static {
        products = new HashMap<>();
        stock = new HashMap<>();
        orders=new HashMap<>();
        products.put("123456", 100000);
        stock.put("123456", 100000);
    }

    private String queryMap(String productId) {
        return "国庆活动，皮蛋粥特价，限量份" + products.get(productId) + "还剩:" + stock.get(productId) + "份,该商品成功下单用户数目：" + orders.size() + "人";
    }

    public String querySecKillProductInfo(String productId){
        return queryMap(productId);
    }

    public void orderProductMockDifUser(String productId){

        long time=System.currentTimeMillis()+TIMEOUT;
        if(!redisLock.lock(productId,String.valueOf(time))){
            throw new RuntimeException();
        }
        int stockNum=stock.get(productId);
        if(stockNum==0){
            throw new RuntimeException();
        }else{
            Random r=new java.util.Random();
            orders.put(r.nextInt()+"",productId);
            stockNum=stockNum-1;
            try {
                Thread.sleep(100);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
            stock.put(productId,stockNum);
        }
        redisLock.unlock(productId,String.valueOf(time));
    }
}
